<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;

class UpController extends Controller
{

    public function index()
    {
        //获取用户id
        $id = session('user') -> id;

        $data = DB::table('image') -> where('userid',$id) -> orderBy('imagedate','desc') -> get();
        $date = $id;
        return view('home.userUpload',['data' => $data,'date' => $date]);
    }

    //图片上传
    public function upload(Request $request)
    {
    	//获取用户id
        $id = session('user') -> id;

        $date = $request -> except('_token');
        //获取分类id
        $categoryid = $date['order'];

        //获取时间
        $created_at = date('Y-m-d H:i:s',time());

        //处理图片
        if($request -> hasFile('pic'))
        {   
            foreach ($date['pic'] as $k => $v) {
                //获取图片扩展名
                $extension = $v -> getClientOriginalExtension();

                //拼接图片名称
                $fileName = str_random(32).'.'.$extension;
                $dir = 'img/'.$id;

                //判断目录是否存在
                if(!file_exists($dir))
                {
                    mkdir($dir,0777,true);
                }

                //移动
                $move = $v -> move($dir,$fileName);

                //判断是否移动成功
                if(!$move)
                {
                   return back() -> with(['info' => '上传失败']); 
                }

                //数据库添加
                $res = DB::table('image') -> where('userid',$id) -> insert(['categoryid' => $categoryid,'userid' => $id,'imageURL' => $fileName,'imagedate' => $created_at]);
                if(!$res)
                {
                    return back() -> with(['info' => '上传失败']); 
                }
            }

            $date = 'uID_'.$id;  
            $data = DB::table('image') -> where('userid',$id) -> orderBy('imagedate','desc') -> get();

            return redirect('myZone') -> with(['info' => '上传成功']);

        }else{
            return back() -> with(['info' => '您没有上传图片']); 
        }
    }
}
